<?php

namespace App\Services\Auth;

use App\Criteria\Auth\ModuleButton\ModuleCriteria;
use App\Entities\Auth\ModuleButton;
use App\Repositories\Auth\ModuleButtonRepository;
use Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Libraries\Common\Tree;
use Spatie\Fractalistic\Fractal;
use Spatie\Fractalistic\ArraySerializer;
use App\Transformers\Auth\ModuleButton\TreeTransformer;

class ModuleButtonService
{
    protected $repository;

    public function __construct(ModuleButtonRepository $repository)
    {
        $this->repository = $repository;
    }

    public function getPageList()
    {
        try {
            $request = request();

            $this->repository->pushCriteria(ModuleCriteria::class);
            $res = $this->repository->paginate($request['limit'])->toArray();

            $data = [
                'code' => 0,
                'msg' => '正在请求中...',
                'count' => $res['total'],
                'data' => $res['data'],
            ];

            return $data;
        } catch (Exception $ex) {
            Log::error('Module Button getPageList Error', [$ex->getMessage()]);

            return null;
        }
    }

    public function create($data)
    {
        try {
            $button = new ModuleButton($data);
            $this->repository->SaveData($button);

            return true;
        } catch (Exception $ex) {
            Log::error('Module Button Create Error', [$ex->getMessage()]);

            return false;
        }
    }

    public function update($id, $data)
    {
        try {
            $button = new ModuleButton($data);
            $this->repository->SaveData($button, $id);

            return true;
        } catch (Exception $ex) {
            Log::error('Module Button Update id="'.$id.'" Error', [$ex->getMessage()]);

            return false;
        }
    }

    public function show($id)
    {
        try {
            return $this->repository->find($id);
        } catch (Exception $ex) {
            Log::error('Module Button Load id="'.$id.'" Error', [$ex->getMessage()]);

            return null;
        }
    }

    public function remove($ids)
    {
        DB::beginTransaction();
        try {
            $this->repository->delete($ids);

            DB::commit();

            return true;
        } catch (Exception $ex) {
            DB::rollBack();
            Log::error('Module Button Delete'.$ids.' Error', [$ex->getMessage()]);

            return false;
        }
    }

    public function getTree()
    {
        $data = $this->repository->all();
        $treeData = Fractal::create()
            ->serializeWith(new ArraySerializer())
            ->collection($data, new TreeTransformer())
            ->toArray();

        return Tree::makeTree($treeData, ['expanded_key' => 'open']);
    }
}
